<template>
    <div class="user_recipients_list_container">
        <ZWSearch
            row-num="3"
            :option="searchOption"
            @search="search"
            @reset="reset"
            @input="inputSearch"
            @expand="expandSearch" />
        <ZWTable
            ref="orderTableRef"
            class="table-box"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @select="onSelect"
            @selection-change="onSelectionChange"
            @select-all="onSelectAll"
            @dataChange="tableDataChange">
            <!--暂时隐藏-->
            <!-- <template #headerOperateLeft>
          <div style="display: flex; align-items: center">
            <div style="font-size: 13px; line-height: 1; margin-right: 10px">最近同步时间：{{ updateTime }}</div>
            <div style="display: flex; align-items: center">
              <el-dropdown style="margin-left: 10px">
                <span style="color: #ff6b00; font-size: 12px; cursor: pointer; line-height: 1; padding-right: 6px">
                  同步订单收货人<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="synchronousData">
                      直接同步&nbsp;
                      <el-tooltip class="box-item" effect="light" :content="synchronousTips" placement="top">
                        <el-image src="/static/question.png" style="width:16px;height:16px"></el-image>
                      </el-tooltip>
                    </el-dropdown-item>
                    <el-dropdown-item @click="synchronousProData">
                      高级同步&nbsp;
                      <el-tooltip class="box-item" effect="light" :content="synchronousProTips" placement="top">
                        <el-image src="/static/question.png" style="width:16px;height:16px"></el-image>
                      </el-tooltip>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-tooltip class="box-item" effect="light" :content="synchronousOrderTips" placement="top">
                <el-image src="/static/question.png" style="width:16px;height:16px"></el-image>
              </el-tooltip>
            </div>
            <div style="font-size: 13px; line-height: 1; margin-left: 10px; cursor: pointer; color: #ff6b00" v-if="isShowRefresh" @click="reset">刷新</div>
          </div>
        </template> -->
            <template #headerOperate>
                <el-button @click="settingPro">高级设置</el-button>
                <el-dropdown style="margin-left: 10px">
                    <el-button type="primary">
                        批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item :disabled="!checkList.length" @click="exportDistribution">
                                批量分配
                            </el-dropdown-item>
                            <!-- 暂时隐藏 2022-11-23 -->
                            <!-- <el-dropdown-item :disabled="!checkList.length" @click="exportSome">批量导出</el-dropdown-item>
                            <el-dropdown-item @click="exportAll">导出所有</el-dropdown-item> -->
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </template>
        </ZWTable>
    </div>
    <!-- 查看 收件人 详细地址 弹框 -->
    <address-detail-popover
        v-model="isShowPopover"
        :popover-address="popoverAddress"
        :popover-top="popoverTop"
        :popover-left="popoverLeft" />
    <Dialog :app-dialog="appDialogSettingPro">
        <div class="title">
            <span class="before">自动同步scrm客户</span>
            <el-switch v-model="settingProForm.auto_sync" :active-value="1" :inactive-value="2" class="ml-2" />
            <span class="after">
                开启后，订单收货人将根据手机号自动分配scrm客户，如果匹配不上，将自动创建新的scrm客户，并按规则分配员工跟进。
            </span>
        </div>
        <el-form ref="settingProFormRef" :model="settingProForm" :rules="settingProFormRules" label-width="auto">
            <el-form-item label="客户公海" prop="cust_seas_id">
                <el-select v-model="settingProForm.cust_seas_id" placeholder="请选择客户公海">
                    <el-option v-for="item in seas_ids" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="客户来源" prop="cust_source_id">
                <div class="custSource">
                    <el-select v-model="settingProForm.cust_source_id" placeholder="请选择客户来源">
                        <el-option v-for="item in source_ids" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                    <div class="tips">
                        还没有？
                        <span @click="toAdd">去添加</span>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="客户阶段" prop="cust_stage_id">
                <el-select v-model="settingProForm.cust_stage_id" placeholder="请选择客户阶段">
                    <el-option v-for="item in stage_ids" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="分配员工" prop="dist_work_users">
                <select-depart
                    v-model="settingProForm.dist_work_users"
                    :creators="settingProForm.dist_work_users_creators"
                    multiple />
            </el-form-item>
            <el-form-item label="分配方式">
                <el-radio-group v-model="settingProForm.dist_type">
                    <el-radio :label="1">随机分配</el-radio>
                    <el-radio :label="2">平均分配</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="客户标签" prop="cust_tags">
                <select-label
                    v-model="settingProForm.cust_tags"
                    :creators="settingProForm.cust_tags_creators"
                    multiple />
            </el-form-item>
        </el-form>
    </Dialog>

    <!-- 高级同步 -->
    <Dialog :app-dialog="appDialogSynchronousPro">
        <el-form
            ref="synchronousProFormRef"
            :model="synchronousProForm"
            :rules="synchronousProFormRules"
            label-width="auto">
            <el-form-item label="归属店铺" prop="shop_id">
                <select-store v-model="synchronousProForm.shop_id" @change="changeStore" />
            </el-form-item>
            <el-form-item label="下单时间" prop="order_time">
                <el-date-picker
                    v-model="synchronousProForm.order_time"
                    :editable="false"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="daterange"
                    range-separator="—"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    prefix-icon="Calendar"
                    size="small"
                    :disabled-date="disabledDate"
                    @calendar-change="handleChange"
                    @focus="handleFocus" />
                <div style="font-size: 12px">最多选择{{ impose }}天的数据</div>
            </el-form-item>
            <el-form-item label="订单处理" prop="method">
                <el-radio-group v-model="synchronousProForm.method" class="holiday_box">
                    <el-radio class="holiday_item" :label="1" :value="1">跳过不处理</el-radio>
                    <el-radio class="holiday_item" :label="2" :value="2">更新处理</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
    </Dialog>

    <ZWDepart ref="DepartRef" :type="1" @submit="getDepart"></ZWDepart>
</template>

<script setup lang="tsx">
import { reactive, ref, onMounted, computed, nextTick } from 'vue';
import { ElMessage, ElButton, ElPopper, ElPopover } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import Dialog from '@/components/Dialog.vue';
import { getCustomerOpenseaSelect } from '@/api/customer/manage/list';
import { sourceList } from '@/view/customer/manage/configure/api';
import { stageList } from '@/api/customerCenter/labellagroup';
import { getDictEnum } from '@/api/ecommerce/storeManage';
import { synchronous, synchronousPro } from '@/api/ecommerce/userManage';
import {
    settingProfessional,
    getConsigneeList,
    exportConsigneeData,
    batchAssignStaff,
    getAdvancedSetting,
    exportAllData
} from '@/api/ecommerce/userManage';
import ZWSearch from '@/components/zw/search-form/SearchForm';
import ZWTable from '@/components/zw/table/Table';
import ZWDepart from '@/components/ZWDepart.vue';
import selectDepart from '@/components/customerCenter/selectDepart.vue';

import addressDetailPopover from '../../components/addressDetailPopover.vue';
import selectStore from '../../components/selectStore.vue';
import selectLabel from '../../components/selectLabel.vue';
import tableHeaderTooltip from '../../components/tableHeaderTooltip.vue';
import tablePopover from './components/tablePopover.vue';

import cityData from '@/assets/js/city';
import lodash from 'lodash';
import router from '@/router';
import { div } from '@/utils/math';
import { downloadFile } from '@/utils/utils';

const orderTableRef = ref<HTMLElement | null>(null);
const synchronousProFormRef = ref<FormInstance>();

const pickDay = ref();
const impose = ref(180);

const calcDefaultDate = () => {
    const nowDate = new Date().getTime();
    const lastDate = nowDate - 1000 * 60 * 60 * 24 * 365;
    const now_year = new Date().getFullYear();
    let now_month = new Date().getMonth() + 1;
    let now_day = new Date().getDate();

    const last_year = new Date(lastDate).getFullYear();
    let last_month = new Date(lastDate).getMonth() + 1;
    let last_day = new Date(lastDate).getDate();

    now_month = now_month > 9 ? now_month : `0${now_month}`;
    now_day = now_day > 9 ? now_day : `0${now_day}`;

    last_month = last_month > 9 ? last_month : `0${last_month}`;
    last_day = last_day > 9 ? last_day : `0${last_day}`;

    return [`${last_year}-${last_month}-${last_day}`, `${now_year}-${now_month}-${now_day}`];
};

const defaultDate = calcDefaultDate();
const defaultParams = reactive<any>({
    created_at: defaultDate
});

const tips = ref<string>('删除后，该店铺数据将不能同步，店铺关联的数据也会清除，您确定要删除该店铺吗？');
const synchronousOrderTips = ref<string>('手机号相同为同一个收件人，姓名、详细地址将会冗余存储');
const synchronousTips = ref<string>('同步所有店铺最近180天的数据');
const synchronousProTips = ref<string>('同步选择指定店铺指定时间段的数据');
const settingProFormRef = ref<FormInstance>();
const DepartRef = ref<any>(null);

const updateTime = ref<string>('');

const checkList = ref<any>([]);
const checkListSign = ref<any>([]);
let paramsSearch = reactive<any>(null);

const seas_ids = reactive<any>([]);
const source_ids = reactive<any>([]);
const stage_ids = reactive<any>([]);

const isShowPopover = ref<boolean>(false);
const popoverAddress = reactive<any>([]);
const popoverTop = ref<number>(0);
const popoverLeft = ref<number>(0);
const isShowRefresh = ref<boolean>(false);

const cust_tips = ref<any[]>([
    {
        id: 1,
        text: '绑定客易达客户信息'
    },
    {
        id: 2,
        text: '淘宝订单：通过订单收件人手机号码匹配客易达客户'
    },
    {
        id: 3,
        text: '客易达订单、自营店铺订单：通过订单购买账号授权的手机号来匹配客易达客户'
    }
]);

type stateType = {
    searchParams: any;
    deleteId: number | string;
};
const state = reactive<stateType>({
    searchParams: lodash.cloneDeep(defaultParams),
    deleteId: ''
});

type settingProFormType = {
    sync_type?: string | number;
    auto_sync?: string | number;
    cust_seas_id?: string | number;
    cust_source_id?: string | number;
    cust_stage_id?: string | number;
    dist_work_users: any[];
    dist_work_users_creators: any[];
    dist_type?: string | number;
    cust_tags?: [];
    cust_tags_creators?: [];
};
const settingProForm = reactive<settingProFormType>({
    sync_type: 2,
    auto_sync: 2,
    cust_seas_id: '',
    cust_source_id: '',
    cust_stage_id: '',
    dist_work_users: [],
    dist_work_users_creators: [],
    dist_type: 1,
    cust_tags: [],
    cust_tags_creators: []
});
const settingProFormRules = reactive<FormRules>({
    cust_seas_id: [{ required: true, message: '请选择客户公海', trigger: 'change' }],
    cust_source_id: [{ required: true, message: '请选择客户来源', trigger: 'change' }],
    cust_stage_id: [{ required: true, message: '请选择客户阶段', trigger: 'change' }],
    dist_work_users: [{ required: true, message: '请选择分配员工', trigger: 'change' }],
    cust_tags: [{ required: true, message: '请选择客户标签', trigger: 'change' }]
});

// 高级同步
type synchronousProFormType = {
    shop_id?: string | number;
    order_time: string[];
    method: number | string;
};
const synchronousProForm = reactive<synchronousProFormType>({
    shop_id: '',
    order_time: [],
    method: 1
});
const synchronousProFormRules = reactive<FormRules>({
    shop_id: [{ required: true, message: '请选择归属店铺', trigger: 'change' }],
    order_time: [{ required: true, message: '请选择下单时间', trigger: 'change' }]
});

const searchOption = computed(() => {
    return [
        {
            label: '店铺类型',
            name: 'retail_shop_type',
            value: '',
            type: 'select',
            placeholder: '请选择店铺类型',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    const params = { dict_id: 1 };
                    getDictEnum(params).then((res: any) => {
                        const targetArr: any = [];
                        res.forEach((item: any) => {
                            targetArr.push(item);
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '归属店铺',
            name: 'retail_shop_id',
            value: '',
            type: 'input',
            placeholder: '请输入店铺ID｜名称搜索'
        },
        {
            label: '收货人信息',
            name: 'consignee_keyword',
            value: '',
            type: 'input',
            placeholder: '请输入收货人姓名｜手机号搜索'
        },
        {
            label: '详细地址',
            name: 'detail_address',
            value: '',
            type: 'input',
            placeholder: '请输入收货人详细地址搜索'
        },
        {
            label: '行政区域',
            name: 'region_code',
            value: [],
            type: 'cascader',
            placeholder: '请选择行政区域',
            options: cityData,
            props: {
                checkStrictly: true, // 是否严格的遵守父子节点不互相关联
                emitPath: false,
                multiple: false,
                label: 'name',
                value: 'code'
            }
        },
        {
            label: '归属员工',
            name: 'belong_work_user_id',
            value: [],
            type: 'select',
            placeholder: '全部',
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '绑定客户',
            name: 'bind_cust',
            value: '',
            type: 'input',
            placeholder: '请输入客户姓名｜手机号搜索'
        },
        {
            label: '创建时间',
            name: 'created_at',
            value: defaultDate,
            default: defaultDate,
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            disabledDate: (date: Date) => {
                return new Date(date).getTime() > new Date().getTime();
            }
        }
    ];
});

const tableOption = [
    {
        type: 'selection',
        width: 65,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'name',
        label: '收货人姓名',
        width: 160
    },
    {
        prop: 'mobile',
        label: '手机号',
        width: 160
    },
    {
        prop: 'region',
        label: '行政区域',
        width: 260,
        render({ row }: any) {
            const { region: region = [] } = row;
            if (region?.length == 1) {
                return region.join(';');
            } else if (region?.length > 1) {
                return <tablePopover content={region} name="区域" />;
            } else {
                return '--';
            }
        }
    },
    {
        //
        prop: 'detail_address',
        label: '详细地址',
        minWidth: 330,
        render({ row }: any) {
            const { detail_address: detail_address = [] } = row;
            if (detail_address.length == 1) {
                const { contact, address } = detail_address[0];
                return (
                    <div style="">
                        <div>{contact + '-' + address || ''}</div>
                    </div>
                );
            } else if (detail_address.length > 1) {
                return <tableTooltip content={detail_address} />;
            } else {
                return '--';
            }
        }
    },
    {
        //
        prop: 'bind_cust',
        label: '绑定客户',
        width: 180,
        render({ row }: any) {
            if (row.bind_cust) {
                const {
                    bind_cust: { id, name, mobile, type: type = 1 }
                } = row;
                return (
                    <div
                        class="bindCust"
                        onClick={() => {
                            // router.push(`/customer/manage/list/detail?id=${id}&type=${type}`)

                            const url = `/customer/manage/list/detail?id=${id}&type=${type}`;
                            window.open(url, '_blank');
                        }}>
                        <span>{`${name}(${mobile})`}</span>
                    </div>
                );
            } else {
                return '--';
            }
        },
        renderHeader({ row, index }: any) {
            return <tableHeaderTooltip title="绑定客户" content={cust_tips.value} />;
        }
    },
    {
        prop: 'belong_work_name',
        label: '归属员工',
        width: 180,
        render({ row }: any) {
            return row?.belong_work_name || '--';
        }
    },
    {
        prop: 'shop_type_name',
        label: '店铺类型',
        width: 180,
        render({ row }: any) {
            return <elPopoverTips content={row.shop_type_name} isArr={true} />;
        }
    },
    {
        prop: 'retail_shop',
        label: '归属店铺',
        width: 180,
        render({ row }: any) {
            return <elPopoverTips content={row.retail_shop} isArr={true} />;
        }
    },
    {
        prop: 'created_at',
        label: '创建时间',
        minWidth: 200
    },
    {
        prop: 'updated_at',
        label: '更新时间',
        minWidth: 200
    },
    {
        prop: 'operate',
        label: '操作',
        width: 160,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }: any) {
            if (row?.bind_cust?.id) {
                return (
                    <ElButton
                        size="small"
                        onClick={() => {
                            checkListSign.value = row?.bind_cust?.id ? [row?.bind_cust?.id] : [];
                            DepartRef.value.multiple = false;
                            DepartRef.value.departVisble = true;
                        }}>
                        {row?.belong_work_name ? '重新分配' : '分配'}
                    </ElButton>
                );
            } else {
                return '--';
            }
        }
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const expandSearch = () => {
    nextTick(() => {
        orderTableRef.value.getTableH();
    });
};

const disabledDate = (time: number) => {
    if (!pickDay.value) {
        return false;
    }
    if (impose.value) {
        const con1 = new Date(pickDay.value).getTime() - impose.value * 24 * 60 * 60 * 1000;
        const con2 = new Date(pickDay.value).getTime() + impose.value * 24 * 60 * 60 * 1000;
        return time < con1 || time > con2;
    }
    return false;
};
const handleChange = (val: Date[]) => {
    if (impose.value) {
        const [pointDay] = val;
        pickDay.value = pointDay;
    }
};
const handleFocus = () => {
    pickDay.value = null;
};

const inputSearch = (val: any) => {
    paramsSearch = val;
};
const search = (data: any): void => {
    orderTableRef.value.clearSelection();
    const { created_at: created_at = [] } = data;
    if (created_at?.length) {
        const diff = new Date(created_at[1]).getTime() - new Date(created_at[0]).getTime();
        if (diff / (1000 * 60 * 60 * 24) > 365) {
            ElMessage.warning('创建时间选择范围在365天内');
        } else {
            data.belong_work_user_id = data.belong_work_user_id ? [data.belong_work_user_id] : [];
            state.searchParams = data;
        }
    } else {
        ElMessage.warning('请选择创建时间');
    }
};
const reset = (): void => {
    orderTableRef.value.clearSelection();
    state.searchParams = lodash.cloneDeep(defaultParams);
};
const fetchApi = (): any => {
    return new Promise((resolve: any): any => {
        const page_size: string | number = 15;
        const params = {};
        resolve([params, getConsigneeList]);
    });
};

const synchronousData = async () => {
    if (await synchronous({})) {
        isShowRefresh.value = true;
        ElMessage.success('同步成功');
        reset();
    }
};
const synchronousProData = () => {
    appDialogSynchronousPro.visible = true;
};

const cancelHandel = (): void => {
    appDialogSettingPro.visible = false;
    settingProForm.auto_sync = 2;
    settingProForm.cust_seas_id = '';
    settingProForm.cust_source_id = '';
    settingProForm.cust_stage_id = '';
    settingProForm.dist_work_users = [];
    settingProForm.dist_work_users_creators = [];
    settingProForm.dist_type = 1;
    settingProForm.cust_tags = [];
    settingProForm.cust_tags_creators = [];
};
const submitHandel = async () => {
    if (!settingProFormRef.value) return;
    await settingProFormRef.value.validate((valid: any): void => {
        if (valid) {
            settingProfessional(settingProForm).then(() => {
                ElMessage.success('设置成功');
                cancelHandel();
                state.searchParams = { ...state.searchParams };
            });
        }
    });
};
const appDialogSettingPro = reactive<any>({
    visible: false,
    title: '高级设置',
    width: '660px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
});

// 高级同步
const cancelHandelSynchronousPro = (): void => {
    appDialogSynchronousPro.visible = false;
};
const submitHandelSynchronousPro = async () => {
    if (!synchronousProFormRef.value) return;
    await synchronousProFormRef.value.validate(async (valid: any): Promise<void> => {
        if (valid) {
            if (await synchronousPro(synchronousProForm)) {
                isShowRefresh.value = true;
                ElMessage.success('同步成功');
                appDialogSynchronousPro.visible = false;
                reset();
            }
        }
    });
};
const appDialogSynchronousPro = reactive<any>({
    visible: false,
    title: '高级同步',
    width: '600px',
    cancel: cancelHandelSynchronousPro,
    submit: submitHandelSynchronousPro,
    cancelText: '取消',
    submitText: '确定'
});

const changeStore = (value: any) => {
    if (value?.length && value[0].source == 2) {
        impose.value = 90;
    }
    synchronousProFormRef.value.validateField('shop_id');
};

// 选中表格 checkbox
const onSelect = (selection: any, row: any) => {
    checkList.value = selection;
};
// 选择项变更
const onSelectionChange = (selection: any) => {};
// 全选
const onSelectAll = (selection: any) => {
    checkList.value = selection;
};
const tableDataChange = (data: any): void => {
    updateTime.value = data.last_sync_time;
};

const getSeaList = () => {
    seas_ids.splice(0);
    getCustomerOpenseaSelect({ type: 1 }).then((res: any) => {
        seas_ids.push(...res);
    });
};
const getSourceList = () => {
    source_ids.splice(0);
    sourceList({ page: 1, page_size: 99 }).then((res: any) => {
        source_ids.push(...res.data);
    });
};
const getStageList = () => {
    stage_ids.splice(0);
    stageList({ page: 1, page_size: 99 }).then((res: any) => {
        stage_ids.push(...res);
    });
};

const toAdd = () => {
    router.push('/customer/manage/configure');
};

const settingPro = async (): Promise<void> => {
    const params = { sync_type: 2 };
    const res = await getAdvancedSetting(params);
    if (!res) {
        settingProForm.auto_sync = 2;
    } else {
        const {
            auto_sync: auto_sync = 2,
            cust_seas_id: cust_seas_id = '',
            cust_source_id: cust_source_id = '',
            cust_stage_id: cust_stage_id = '',
            dist_type: dist_type = 1,
            dist_work_users: dist_work_users_creators = [],
            cust_tags: cust_tags_creators = []
        } = res;
        settingProForm.auto_sync = auto_sync;
        settingProForm.cust_seas_id = cust_seas_id;
        settingProForm.cust_source_id = cust_source_id;
        settingProForm.cust_stage_id = cust_stage_id;
        settingProForm.dist_type = dist_type;
        settingProForm.dist_work_users_creators = dist_work_users_creators;
        settingProForm.cust_tags_creators = cust_tags_creators;
    }
    appDialogSettingPro.visible = true;
};

const getDepart = async (res: any, flag: boolean): Promise<void> => {
    if (!flag) {
        if (res?.length) {
            let customer_list: any[] = [];
            if (DepartRef.value.multiple) {
                customer_list = checkList.value.map((ite: any) => ite?.bind_cust?.id ?? '');
            } else {
                customer_list = checkListSign.value;
            }
            const work_user_list = res.map((item: any) => item.id);
            const params = { customer_list, work_user_list };
            if (await batchAssignStaff(params)) {
                DepartRef.value.selectedMember = [];
                ElMessage.success('分配成功');
                DepartRef.value.departVisble = false;
                orderTableRef.value?.clearSelection();
                state.searchParams = { ...state.searchParams };
            }
        }
    }
};
const exportDistribution = (): void => {
    if (checkList.value.length) {
        const customer_list = checkList.value.map((ite: any) => ite?.bind_cust?.id ?? '');
        if (customer_list.some((ite: any) => !ite)) {
            ElMessage.warning('请选择已有绑定客户的收件人');
            return;
        }
        DepartRef.value.multiple = true;
        DepartRef.value.departVisble = true;
    }
};
const exportSome = async (): Promise<void> => {
    if (checkList.value.length) {
        const params = {
            consignee_ids: checkList.value.map((ite: any) => ite?.id)
        };
        const { file_url: href = '' } = await exportConsigneeData(params);
        if (href) {
            downloadFile(href);
            ElMessage.success('导出成功');
        }
    }
};
const exportAll = async (): Promise<void> => {
    const params = lodash.cloneDeep(paramsSearch);
    const { file_url: href = '' } = await exportAllData(params);
    if (href) {
        downloadFile(href);
        ElMessage.success('导出成功');
    }
};

const checkAddress = (row: any, $event: any): void => {
    const { detail_address } = row;
    const { x, y } = $event;
    isShowPopover.value = true;
    popoverTop.value = y;
    popoverLeft.value = x;
    popoverAddress.splice(0);
    popoverAddress.push(...detail_address);
};

onMounted(() => {
    getSeaList();
    getSourceList();
    getStageList();
});
</script>

<style lang="scss" scoped>
.user_recipients_list_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.title {
    display: flex;
    padding: 6px 0 16px;

    .before {
        white-space: nowrap;
        padding-right: 6px;
    }

    .after {
        padding-left: 6px;
        line-height: 1.5;
    }
}

.custSource {
    display: flex;
    align-items: center;

    .tips {
        margin-left: 10px;

        span {
            color: #ff6b00;

            &:hover {
                cursor: pointer;
            }
        }
    }
}

:deep(.detail_address) {
    width: 300px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

:deep(.view_address) {
    border-bottom: 1px solid #eaeaea;
}

:deep(.bindCust) {
    display: flex;
    align-items: center;
    cursor: pointer;
    color: #ff6b00;
}
</style>
